package com.redxiii.spike.services.secure;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.redxiii.spike.api.communication.SecureChannelAuth;
import com.redxiii.spike.api.communication.SecureChannelService;

/**
 * @author Daniel Filgueiras
 * @since 11/01/2012
 */
public class SSLService implements SecureChannelService {

	private static final Logger logger = LoggerFactory.getLogger(SSLService.class);
	private static final AtomicInteger CHID = new AtomicInteger(1);
	private Map<Integer,Socket> sockets = Collections.synchronizedMap(new HashMap<Integer,Socket>());
	private boolean keepAlive = true;
	private SecureChannelAuth channelAuth;
	
	
	@Override
	public void run() {
		logger.info("XMPP Service started");
		try {
			while(keepAlive) {
				ServerSocket serverSocket = null;
				try {
					if (channelAuth != null) {
						serverSocket = new ServerSocket();
						serverSocket.bind(new InetSocketAddress("localhost", 9801));
						Socket socket = serverSocket.accept();
						Channel channel = new Channel(CHID.getAndIncrement(), socket);
						
						new Thread(channel, Thread.currentThread().getName() + ".Channel-" + channel.id).start();
					}
				} catch (IOException e) {
					if (serverSocket != null) {
						try {	serverSocket.close();	} catch (IOException e1) {}
					}
				}
				Thread.sleep(1000 * 30);
				
			}
		} catch (InterruptedException e) {
			
		}
	}
	
	class Channel implements Runnable {

		private int id;
		private Socket socket;
		
		private Channel(int id, Socket socket) {
			this.id = id;
			this.socket = socket;
		}

		@Override
		public void run() {
			logger.debug("Channel {} active", id);
			try {
				int maxIteration = 4;
				boolean authorized = false;
				
				InputStream in = socket.getInputStream();
				StringBuilder buffer = new StringBuilder();
				while (keepAlive && socket.isConnected()) {
					Thread.sleep(1000 * 5);
					
					if (maxIteration > 0 || authorized)
						continue;
					
					byte[] bytes = new byte[1024];
					while (in.available()> 0) {
						int read = in.read(bytes);
						buffer.append(new String(bytes, 0, read));
					}
				}
			} catch (InterruptedException e) {
			} catch (IOException e) {
			}
			
			logger.debug("Channel {} closed", id);
			sockets.remove(this.id);
			logger.debug("Channel {} ended", id);
		}
		
	}
	
	@Override
	public void setAuthenticator(SecureChannelAuth auth) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean isConnected(int channelId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public InputStream getInputStream(int channelId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public OutputStream getOutputStream(int channelId) {
		// TODO Auto-generated method stub
		return null;
	}

	

}
